const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

/**
 * 节次合并
 * @param {string[]} table 周空闲教室
 */
const mergeDuring = (table) => {
  const need = {}
  for (let i = 1; i <= 11; i++) {
    if (i % 2 === 0) continue
    for (let j = i + 1; j <= 12; j++) {
      if (j % 2 !== 0) continue
      need[`${i}-${j}`] = []
    }
  }

  for (let i = 1; i <= table.length; i++) {
    for (const e of table[i - 1]) {
      let do_ = false
      for (let j = i + 1; j <= table.length; j++) {
        const index = table[j - 1].indexOf(e)
        if (index === -1) {
          need[`${i * 2 - 1}-${(j - 1) * 2}`].push(e)
          do_ = true
          break
        }
        table[j - 1].splice(index, 1)
      }
      if (!do_) {
        need[`${i * 2 - 1}-${table.length * 2}`].push(e)
      }
    }
  }

  const result = {}
  for (const key in need) {
    if (need[key].length !== 0) result[key] = need[key]
  }
  result['上午'] = result['1-4'] || []
  result['下午'] = result['5-8'] || []
  result['晚上'] = result['9-12'] || []
  result['全天'] = result['1-12'] || []

  delete result['1-4']
  delete result['5-8']
  delete result['9-12']
  delete result['1-12']

  return result
}

module.exports = class emptyroomService extends Service {
  /**
   * 爬取空闲教室
   * @param {string} term 学期
   * @param {string} zc 周次*
   * @param {string} week 星期*
   * @param {{label:string, value:string}} jxl 教学楼
   * @param {string} schoolId 校区id
   * @return {Array} *
   */
  async table(term, zc, week, jxl, schoolId) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbxx/jsjy_query2`

    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        typewhere: 'jszq',
        xnxqh: term,
        gnq_mh: '',
        jsmc_mh: '',
        syjs0601id: '',
        xqbh: '',
        jslx: '',
        jxqbh: '',
        jxlbh: jxl.value,
        jsbh: '',
        bjfh: '=',
        rnrs: '',
        jszt: '',
        zc,
        zc2: zc,
        xq: week,
        xq2: week,
        jc: '',
        jc2: '',
        kbjcmsid: '3EB513BA358B41BE9509FAE162AB84C3',
        ssdw: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    // console.log('res.status', res.status)
    const classPeriod = ['1-2', '3-4', '5-6', '7-8', '9-10']
    const ColClassPeriod = [1, 2, 3, 4, 5]
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        console.log('tableList', tableList)
        const tem = []
        for (let i = 0; i < classPeriod.length; i++) {
          tem[i] = []
        }
        for (let i = 3; i < tableList.length; i++) {
          ColClassPeriod.forEach((e) => {
            if (tableList[i][e] === '') {
              tem[e - 1].push(tableList[i][0].replace(/\([^)]*\)/g, ''))
            }
          })
        }
        // console.log('tem', tem)
        return {
          campus_id: this.ctx.state.campusId,
          school_id: schoolId,
          zc,
          week,
          building: jxl.label,
          data: mergeDuring(tem),
        }
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return {}
  }
}
